//
//  SEAuthViewModel.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/18.
//

import UIKit

class SEAuthViewModel: SEBaseViewModel {

    var loginModel = SELoginModel()

    var userInfoModel = SEUserInfoModel()

    var checkRegisterHandler: ((Bool, SEHttpStatus) -> Void)?

    var msgCodeHandler: ((SEHttpStatus) -> Void)?

    var account: String = ""
    var code: String = ""

    var isAgree: Bool = false

    func saveAuthToken() {
        UserDefaults.authToken = loginModel.accessToken
    }
    func saveUserAccountInfo() {
        let isFemale = userInfoModel.idCard.subString(index: userInfoModel.idCard.count - 2, length: 1).intValue % 2 == 0
        UserDefaults.userFemale = isFemale
        UserDefaults.userId = userInfoModel.userId
        UserDefaults.xylinkAccount = userInfoModel.videoAccount
        if UserDefaults.remberAccountAndPsd {
            UserDefaults.userAccount = account
        } else {
            UserDefaults.removeUserAccount()
        }
    }
    func removeAuthToken() {
        UserDefaults.removeAuthToken()
    }

    var checkLogin: String? {
        if account.isEmpty {
            return "请输入手机号"
        }
        if code.isEmpty {
            return "请输入验证码"
        }
        if !isAgree {
            return "请阅读并同意用户须知"
        }
        return nil
    }


    /// APIRequest

    /// 获取验证码
    func requestMsgCode() {
        if account.isEmpty {
            SEHUD.showError(message: "请输入手机号")
            return
        }
        SEHttpManager.shared.request(SEAuthAPI.getMsg(phone: account), model: Any.self, withLoading: true) { result, status in
            self.msgCodeHandler?(status)
        }
    }

    /// 检查用户是否已经注册
    func requestCheckRegister() {
        if let msg = checkLogin {
            SEHUD.showError(message: msg)
            return
        }
        SEHttpManager.shared.request(SEAuthAPI.checkRegister(phone: account, code: code), model: [String: Bool].self, withLoading: true) { result, status in
            let dic = result ?? ["isRegister": false]
            self.checkRegisterHandler?(dic["isRegister"] ?? false, status)
        }
    }

    /// 登录
    func requestLogin() {
        SEHttpManager.shared.request(SEAuthAPI.login(account: account, code: code), model: SELoginModel.self, withLoading: true) { (model, status) in
            switch status {
            case .success:
                self.loginModel = model ?? SELoginModel()
                self.saveAuthToken()
                self.requestUserInfo()
            default:
                self.updateData?(status)
            }

        }
    }

    /// 查询用户信息
    func requestUserInfo() {
        SEHttpManager.shared.request(SEAuthAPI.userInfo, model: [SEUserInfoModel].self, withLoading: true, completion: { models, status in
            switch status {
            case .success:
                guard let models = models, models.count == 1 else { return }
                self.userInfoModel = models[0]
                self.saveUserAccountInfo()
                self.bindJPushRegistrationID()
            default:
                self.removeAuthToken()
            }
            self.updateData?(status)
        })
    }

    func bindJPushRegistrationID() {
        SEAuthViewModel.bindJPushRegistrationID()
    }

}

extension SEAuthViewModel {
    static func bindJPushRegistrationID() {
        guard !UserDefaults.jpushRegistrationId.isEmpty else { return }
        SEHttpManager.shared.request(SEAuthAPI.bindPushAccount(devNum: UserDefaults.jpushRegistrationId), model: Any.self) { result, status in
            SELog("JPushRegistrationId------\(UserDefaults.jpushRegistrationId)------")
            SELog("BindResult------\(status)------")
        }
    }
}

